var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var colors = require('colors');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');
var routes = require('./routes/index');
var swaggerJSDoc = require('swagger-jsdoc');

const TARGET = process.env.npm_lifecycle_event;
var app = express();

// swagger definition
var swaggerDefinition = {
  info: {
    title: '云盘API',
    version: '1.0.0',
    description: '云盘接口API文档',
  },
  host: 'localhost:3000',
  basePath: '/',
};

// options for the swagger docs
var options = {
  // import swaggerDefinitions
  swaggerDefinition: swaggerDefinition,
  // path to the API docs
  apis: ['./routes/*.js'],
};

// initialize swagger-jsdoc
var swaggerSpec = swaggerJSDoc(options);

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//routes
//接口routes
app.use('/api', routes);

//api
app.get('/spec', function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send(swaggerSpec);
});

//single page logic
if (TARGET == 'dev' || !TARGET) {
  app.use(express.static(path.join(__dirname, '/dist')));
  app.get('*', function response(req, res) {
    res.write(fs.readFileSync(path.join(__dirname, 'dist/index.html')));
    res.end();
  });
} else if(TARGET ==='start'){
  app.use(express.static(path.join(__dirname, '/dist')));
  app.get('*', function response(req, res) {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
  });
}

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (TARGET == 'dev' || !TARGET) {
  app.use(function(err, req, res, next) {
    console.log(err)
    res.status(err.status || 500);
    res.write(err.toString());
    res.end();
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  console.log(err)
  res.status(err.status || 500);
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});


module.exports = app;
